package xyf.p11.other;

/**
 * ClassName: J067_Str2Int
 * Description:
 * Author: xyf
 * Date: 9/16/22 1:14 AM
 * Version: 1.0
 **/
public class J067_Str2Int
{
    public int strToInt(String str)
    {
        if (str == null || str.length() == 0)
        {
            return 0;
        }
        int index = 0;
        while (index < str.length() && str.charAt(index) == ' ')
        {
            index++;
        }
        if (index >= str.length())
        {
            return 0;
        }
        boolean isPositive = true;
        if (str.charAt(index) == '+')
        {
            index++;
        }
        else if (str.charAt(index) == '-')
        {
            index++;
            isPositive = false;
        }

        long res = 0;
        while (index < str.length())
        {
            if (Character.isDigit(str.charAt(index)))
            {
                int cur = str.charAt(index) - '0';
                res = res * 10 + cur;
            }
            else
            {
                break;
            }
            index++;

            long tmpCur = isPositive ? res : res * -1;
            if (tmpCur > Integer.MAX_VALUE)
            {
                return Integer.MAX_VALUE;
            }
            if (tmpCur < Integer.MIN_VALUE)
            {
                return Integer.MIN_VALUE;
            }
        }
        res = isPositive ? res : res * -1;
        return (int) res;
    }
}
